// lib/ui/pages/settings_page.dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// View 只依赖 ViewModel 的 Provider
import '../../providers/settings_viewmodel.dart';

class SettingsPage extends ConsumerStatefulWidget {
  const SettingsPage({super.key});

  @override
  ConsumerState<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends ConsumerState<SettingsPage> {
  late final TextEditingController _nameController;

  @override
  void initState() {
    super.initState();
    // View 从 ViewModel 获取初始状态，不关心数据从哪来
    _nameController = TextEditingController(
      text: ref.read(settingsViewModelProvider).currentName,
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 获取 ViewModel 的引用，以便调用其方法
    final viewModel = ref.read(settingsViewModelProvider.notifier);

    return Scaffold(
      appBar: AppBar(title: const Text('设置 (MVVM)')),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            TextField(
              controller: _nameController,
              decoration: const InputDecoration(labelText: '用户名'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // View 只负责转发用户事件给 ViewModel
                viewModel.updateName(_nameController.text);
                // UI 相关的逻辑留在 View 中
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('用户名已更新!')),
                );
                Navigator.pop(context);
              },
              child: const Text('保存'),
            ),
          ],
        ),
      ),
    );
  }
}
